package com.yiwei.zxp.fragment;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yiwei.zxp.BussinessMainActivity;
import com.yiwei.zxp.R;
import com.yiwei.zxp.activity.BoothPacketActivity;
import com.yiwei.zxp.activity.MyShareMoneyActivity;
import com.yiwei.zxp.adapter.BoothPacketAdapter;
import com.yiwei.zxp.adapter.HomeImageAdapter;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.model.IndexModel;
import com.yiwei.zxp.event.GotoShareMoneyEvent;
import com.yiwei.zxp.event.HomePagerEvent;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.Spans;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 18-5-8.
 */

public class MainHomeFragment extends BaseFragment implements NestedScrollView.OnScrollChangeListener {


    @BindView(R.id.txt_money)
    TextView txtMoney;
    @BindView(R.id.txt_info)
    TextView txtInfo;
    @BindView(R.id.txt_one)
    TextView txtOne;
    @BindView(R.id.txt_two)
    TextView txtTwo;
    @BindView(R.id.txt_three)
    TextView txtThree;
    @BindView(R.id.btn_my_share_money)
    LinearLayout btnMyShareMoney;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.btn_all_packet)
    TextView btnAllPacket;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.list_bottom)
    RecyclerView listBottom;
    @BindView(R.id.view_top)
    View viewTop;
    @BindView(R.id.layout_top)
    LinearLayout layoutTop;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.toolbar)
    V19FrameLayout toolbar;
    Unbinder unbinder;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    private HomeImageAdapter adapter;
    private BoothPacketAdapter boothPacketAdapter;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        scrollView.setOnScrollChangeListener(this);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            headerHeight = getResources().getDimensionPixelSize(R.dimen.y168);
//        } else {
//            headerHeight = getResources().getDimensionPixelSize(R.dimen.y128);
//        }
        headerHeight = getResources().getDimensionPixelSize(R.dimen.y450);
        minHeaderHeight = getResources().getDimension(R.dimen.y98);
        btnMyShareMoney.post(new Runnable() {
            @Override
            public void run() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    int height = Util.getStatusBarHeight(getContext());
                    if (height == 0) {
                        return;
                    }

                    ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) btnMyShareMoney.getLayoutParams();
                    lp.setMargins(0, txtMoney.getTop() + 10, 0, 0);
                    btnMyShareMoney.setLayoutParams(lp);
                }
            }
        });
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getIndex();
            }
        });
//        MoveListener shopCarSettleTouch = new MoveListener(getContext());
//        btnMyShareMoney.setOnTouchListener(shopCarSettleTouch);

        adapter = new HomeImageAdapter(getContext());
        adapter.setOnChooseListener(new HomeImageAdapter.OnChooseListener() {
            @Override
            public void onClick(String title) {
                if (title.equals("购物消费")) {
                    EventBus.getDefault().post(new HomePagerEvent(0));
                    Util.startActivity(getContext(), BussinessMainActivity.class);
                    getActivity().finish();
                } else {
                    ToastUtil.makeText(getContext(), "敬请期待");
                }
            }
        });
        list.setLayoutManager(new GridLayoutManager(getContext(), 4));
        list.setAdapter(adapter);

        boothPacketAdapter = new BoothPacketAdapter(getContext());
        listBottom.setAdapter(boothPacketAdapter);

        EventBus.getDefault().register(this);


    }

    public void getIndex() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }

        refresh.setRefreshing(true);

        Api.api_service.getIndex().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setData(result.datas);
                });
    }

    private void setData(IndexModel.DatasBean item) {
        adapter.update(item.purpose);
        boothPacketAdapter.update(item.combo);

        if (TextUtils.isEmpty(item.user.total)) {
            item.user.total = "";
        }
        Spanned txtLeft = Spans.with(this).font("我的总淘淘币(个)\n", getResources().getDimensionPixelSize(R.dimen.x22), 0xffFFFFFF).
                font(item.user.total, getResources().getDimensionPixelSize(R.dimen.x32), 0xffFFFFFF).style(Typeface.BOLD).
                build();
        txtOne.setText(txtLeft);

        if (TextUtils.isEmpty(item.user.balance)) {
            item.user.balance = "";
        }
        Spanned txtCenter = Spans.with(this).font("可用数量(个)\n", getResources().getDimensionPixelSize(R.dimen.x22), 0xffFFFFFF).
                font(item.user.balance, getResources().getDimensionPixelSize(R.dimen.x32), 0xffFFFFFF).style(Typeface.BOLD).
                build();
        txtTwo.setText(txtCenter);

        if (TextUtils.isEmpty(item.shared_gold.my_location)) {
            item.shared_gold.my_location = "";
        }
        Spanned txtRight = Spans.with(this).font("我的排位\n", getResources().getDimensionPixelSize(R.dimen.x22), 0xffFFFFFF).
                font(item.shared_gold.my_location, getResources().getDimensionPixelSize(R.dimen.x32), 0xffFFFFFF).style(Typeface.BOLD).
                build();
        txtThree.setText(txtRight);

        txtMoney.setText(item.shared_gold.today_gold);
        txtInfo.setText("平台正在发放：第" + item.shared_gold.now_location + "位   总排队数:" + item.shared_gold.total_location + "位\n平台累计赠送淘淘币总数量(个)：" + item.shared_gold.total_gold);
    }

    @Override
    public void onResume() {
        super.onResume();
        getIndex();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(GotoShareMoneyEvent event) {
        Util.startActivity(getActivity(), MyShareMoneyActivity.class);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    @OnClick({R.id.btn_back, R.id.btn_my_share_money, R.id.btn_all_packet})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_my_share_money:
                Util.startActivity(getActivity(), MyShareMoneyActivity.class);
                break;


            case R.id.btn_all_packet:
                Util.startActivity(getActivity(), BoothPacketActivity.class);
                break;
            case R.id.btn_back:
                getActivity().finish();
                break;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    private float headerHeight;
    private float minHeaderHeight;

    @Override
    public void onScrollChange(NestedScrollView v, int x, int y, int oldScrollX, int oldScrollY) {
        //Y轴偏移量
        float scrollY = scrollView.getScrollY();
//        e3483d
        //变化率
        float headerBarOffsetY = headerHeight - minHeaderHeight;//Toolbar与header高度的差值
        float offset = 1 - Math.max((headerBarOffsetY - scrollY) / headerBarOffsetY, 0f);
        if (scrollY >= headerHeight) {
            toolbar.setBackgroundColor(Color.argb(255, 56, 169, 253));
        } else {

            if (scrollY == 0) {

            } else {
                toolbar.setBackgroundColor(Color.argb((int) (offset * 255), 56, 169, 253));
            }
        }
    }

}
